var profileHandler;
var profile = {
    arrXAxis: [], // X轴数据
    arrYAxis: [], // Y轴数据
    maxElevation: -12000, // 最大高程值,int
    minElevation: 9000, // 最小高程值,int
    samplingPoints: [], // 插值后无高程采样点集,C3,[]
    renderPoints: [] // 经过高程处理后的可渲染点,C3,[]
};
var SectionObject;
var linedensity;
var echartstitle;
var spacing;
var tempEntities = [];
var tempPoints = [];

function profileHandle() {
    var tooltip = new GlobeTooltip(viewer.container);
    //绘制贴地线
    profileHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    //左键点击操作
    profileHandler.setInputAction(function (click) {
        //调用绘制点的接口
        SectionObject = $("#SectionObject").val();
        if (SectionObject == 0) {
            position = getPickPositionGlobe(click.position);
            linedensity = 5.0;
            echartstitle = "剖面统计图（间距10米）";
            spacing = 10;
        } else {
            position = getPickPositionGlobe(click.position);
            linedensity = 1.0;
            echartstitle = "剖面统计图（间距0.5米）";
            spacing = 0.5;
        }
        tempPoints.push(position);
        let tempLength = tempPoints.length;
        let point = drawPoint(tempPoints[tempPoints.length - 1]);
        tempEntities.push(point);
        if (tempLength > 1) {
            let pointline = drawPolyline([tempPoints[tempPoints.length - 2], tempPoints[tempPoints.length - 1]]);
            tempEntities.push(pointline);
            profileAnalysis(tempEntities[0].position._value, tempEntities[1].position._value);
            tooltip.setVisible(false);
            profileHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
            profileHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    //鼠标移动
    profileHandler.setInputAction(function(event) {
        var position = event.endPosition;
        if (!Cesium.defined(position)) {
            return;
        }
        var num = tempEntities.length;
        if (num < 1) {
            tooltip.showAt(position, "<p>点击选择起点</p>");
            return;
        }
        var tip = "<p>点击添加下一个点</p>";
        tooltip.showAt(position, tip);
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}


// 绘制点
function drawPoint(position, config) {
    var pointGeometry = null;
    if (SectionObject == 0) {
        pointGeometry = viewer.entities.add({
            position: position,
            point: {
                color: Cesium.Color.RED,
                pixelSize: 10,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
    } else {
        pointGeometry = viewer.entities.add({
            point: new Cesium.PointGraphics({
                color: Cesium.Color.RED,
                pixelSize: 10
            }),
            position: position
        });
    }
    return pointGeometry;
};

//绘制线
function drawPolyline(positions, config) {
    if (positions.length < 1) return;
    var config = config ? config : {};
    var polylineGeometry = viewer.entities.add({
        name: "polyline",
        corridor: {
            positions: positions,
            width: config.width ? config.width : linedensity,
            material: new Cesium.PolylineGlowMaterialProperty({
                color: config.color ? new Cesium.Color.fromCssColorString(config.color) : Cesium.Color.GOLD,
            }),
            depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
                color: config.color ? new Cesium.Color.fromCssColorString(config.color) : Cesium.Color.GOLD,
            }),
        }
    });
    return polylineGeometry;
};

//计算
function calcTwoPointDistanceByEllipsoidGeodesic(startPoint, endPoint) {
    // 以无地形椭球计算地表两点距离
    var geodesic = new Cesium.EllipsoidGeodesic();
    var start = Cesium.Cartographic.fromCartesian(startPoint);
    var end = Cesium.Cartographic.fromCartesian(endPoint);
    geodesic.setEndPoints(start, end);
    var s = geodesic.surfaceDistance;
    s = Math.sqrt(Math.pow(s, 2) + Math.pow(end.height - start.height, 2));
    s = s.toFixed(2);
    return parseFloat(s);
};

function profileAnalysis(start, end) {
    var distance = Cesium.Cartesian3.distance(start, end) / spacing; //设置剖面间距为10米
    var actualSamplingPoints = distance; // 采样点的数目，太大耗时没必要，太小反应不出地形起伏变化，可以自己实际计算，我们随便写个100
    var startPoint = start; // startPoint 要求是C3的
    var endPoint = end; // endPoint 要求是C3的
    // 根据起始点进行线性插值计算（差值点没有实际高程，只有笛卡尔坐标系上的位置）
    profile.arrXAxis.push(0); // 开始准备X轴
    profile.samplingPoints.push(startPoint);
    var distance = 0;
    for (var i = 1; i < actualSamplingPoints; i++) {
        var factor = i / actualSamplingPoints;
        // lerp方法 使用所提供的笛卡尔坐标计算factor处的线性插值或外推
        var cartesian = Cesium.Cartesian3.lerp(startPoint, endPoint, factor, new Cesium.Cartesian3());
        profile.samplingPoints.push(cartesian);
        distance = calcTwoPointDistanceByEllipsoidGeodesic(profile.samplingPoints[i - 1], cartesian);
        // 给每个插值点设置水平轴上位置
        profile.arrXAxis.push(Math.round((profile.arrXAxis[i - 1] + distance) * 10) / 10);
    }
    distance = calcTwoPointDistanceByEllipsoidGeodesic(profile.samplingPoints[i - 1], endPoint);
    profile.arrXAxis.push(Math.round((profile.arrXAxis[i - 1] + distance) * 10) / 10);
    profile.samplingPoints.push(endPoint);
    var positions = [];

    if (SectionObject == 0) {
        // 根据起始点和差值点对每个点计算实际高程

        for (var i = 0; i < profile.samplingPoints.length; i++) {
            var element = profile.samplingPoints[i];
            positions.push(Cesium.Cartographic.fromCartesian(element)); // 转到WGS84坐标系下
        }
        // sampleTerrainMostDetailed方法 在地形数据集的最大可用平铺级别上初始化一个sampleTerrain()请求
        //var promise = Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, positions); // 异步过程
        var promise = Cesium.sampleTerrain(viewer.terrainProvider, 11, positions);
        // 用于异步结束后外部触发，resolve触发后可以知道计算完成，根据计算后数据进行ECharts展示
        var deferred = Cesium.when.defer();
        Cesium.when(promise, function (updatedPositions) {
            var min = 9000;
            var max = -12000;
            for (var kk = 0; kk < updatedPositions.length; kk++) {
                var element = updatedPositions[kk];
                var cartesian = viewer.scene.globe.ellipsoid.cartographicToCartesian(element);
                profile.renderPoints.push(cartesian);
                var tempCarto = Cesium.Cartographic.fromCartesian(cartesian)
                profile.arrYAxis.push(parseFloat(tempCarto.height.toFixed(2))); // 准备Y轴
                // 获取最大最小高程
                if (tempCarto.height < min) {
                    min = tempCarto.height;
                }
                if (tempCarto.height > max) {
                    max = tempCarto.height;
                }
            }
            profile.minElevation = min;
            profile.maxElevation = max;
            deferred.resolve("计算完成，可进行渲染展示");
            echartsView();
        });
        return deferred.promise;
    } else {
        for (var i = 0; i < profile.samplingPoints.length; i++) {
            var element = profile.samplingPoints[i];
            positions.push(element); // 转到WGS84坐标系下
        }
        viewer.scene.clampToHeightMostDetailed(positions).then(function (updatedPositions) {
            var min = 9000;
            var max = -12000;
            for (var kk = 0; kk < updatedPositions.length; kk++) {
                var element = updatedPositions[kk];
                var hei = Cesium.Cartographic.fromCartesian(updatedPositions[kk]).height;
                profile.renderPoints.push(element);
                var tempCarto = Cesium.Cartographic.fromCartesian(element);
                profile.arrYAxis.push(parseFloat(hei.toFixed(2)));
                if (hei < min) { min = hei; }
                if (hei > max) { max = hei; }
            }
            profile.minElevation = min;
            profile.maxElevation = max;
            echartsView();
        })
        return;
    }
}

function echartsView() {
    var e = profile; // 上面的resolve触发后进入这里进行渲染即可
    var html = '<div id="echartsView"></div>';
    layer.open({
        type: 1,
        title: '剖面结果',
        area: ['550px', '320px'],
        shade: 0,
        maxmin: true,
        offset: [ //为了演示，随机坐标
            //($(window).height() - 390) / 2, ($(window).width() - 260) / 2
        ],
        content: html,
        yes: function () {
            profileClearHandle();
        },
        cancel: function(){
            profileClearHandle();
        },
        zIndex: layer.zIndex,
        success: function (layero) {

        }
    });
    var echartsView = document.getElementById("echartsView");
    // echartsView.style.display = 'block';
    var myChart = echarts.init(echartsView);
    var option = {
        grid: {
            left: '3%',
            right: '11.5%',
            bottom: '3%',
            containLabel: true
        },
        title: {
            text: echartstitle,
            x: 'center',
            textStyle: {
                color: '#ffffff'
            }
        },
        toolbox: {
            show: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            feature: {
                restore: { show: true },
                dataView: { show: true, readOnly: true },
                saveAsImage: {
                    show: true,
                    iconStyle: {
                        color: "rgb(128, 128, 128)"
                    }
                }
            }
        },
        tooltip: {
            trigger: 'axis',
            // axisPointer: {
            //     type: "cross",
            //     crossStyle: {
            //         color: "#999"
            //     }
            // },
            formatter: function (params) {
                for (var i = 0; i < e.arrXAxis.length; i++) {
                    if (e.arrXAxis[i] == parseFloat(params[0].axisValue)) {
                        viewer.entities.removeById("_echartspoint_");
                        if (SectionObject == 0) {
                            viewer.entities.add({
                                id: "_echartspoint_",
                                position: e.renderPoints[i],
                                point: {
                                    pixelSize: 4,
                                    color: Cesium.Color.RED,
                                    outlineColor: Cesium.Color.WHITE,
                                    outlineWidth: 2,
                                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                                }
                            })
                        } else {
                            viewer.entities.add({
                                id: "_echartspoint_",
                                position: e.renderPoints[i],
                                point: {
                                    pixelSize: 4,
                                    color: Cesium.Color.RED,
                                    outlineColor: Cesium.Color.WHITE,
                                    outlineWidth: 2
                                }
                            })
                        }
                    }
                }
                return "距起点" + params[0].name + "米，高程" + params[0].value + "米";
            }
        },
        xAxis: {
            name: "距离(m)",
            type: "category",
            boundaryGap: false,
            data: e.arrXAxis,
            nameTextStyle: {
                color: "#0f0"
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: "#0f0"
                }
            }
        },
        yAxis: {
            name: "高程(m)",
            type: "value",
            min: (e.minElevation - 1).toFixed(2), // 最小高程减一是为了看着舒服
            nameTextStyle: {
                color: "#0f0"
            },
            axisLabel: {
                show: true,
                textStyle: {
                    color: "#0f0"
                }
            }
        },
        lineStyle: {
            color: "#A23D35"
        },
        series: [{
            name: "高程值",
            type: "line",
            smooth: true,
            sampling: "average",
            itemStyle: {
                color: "rgb(255, 70, 131)"
            },
            areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                    offset: 0,
                    color: "rgb(174, 21, 0)"
                },
                    {
                        offset: 1,
                        color: "rgb(255, 204, 153)"
                    }
                ])
            },
            data: e.arrYAxis
        }]
    };
    myChart.setOption(option);
    $("#echartsView").resize(function () {
        myChart.resize({ height: $("#echartsView").height(), width: $("#echartsView").width() });
    });
}

function profileClearHandle(){
    tempEntities = [];
    tempPoints = [];
    layer.closeAll();
    viewer.entities.removeAll();
    profileHandler && profileHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK && profileHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE));
}

function profileClear(clear) {
    profile = {
        arrXAxis: [],
        arrYAxis: [],
        maxElevation: -12000,
        minElevation: 9000,
        samplingPoints: [],
        renderPoints: []
    };
    profileHandler && profileHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK && profileHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE));
    tempEntities = [];
    tempPoints = [];
    if (!clear) { removeAllEntities(); }
    layer.closeAll();
}